package com.hzd.service;

import ablaze.framework.api.result.ExecuteResultProcessor;
import ablaze.framework.config.SystemConfig;
import com.hzd.Constant;
import com.hzd.cache.JsApiTicketCache;
import com.hzd.sdk.api.SnsAPI;
import com.hzd.sdk.bean.SnsToken;
import com.hzd.sdk.util.JsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信service
 * @author kent
 * @date 15/11/9.
 */
@Component
public class WxService extends ExecuteResultProcessor {

    @Autowired
    private JsApiTicketCache jsApiTicketCache;

    /**
     * 获取OpenId
     *
     * @param code
     * @return
     */
    public String getOpenId(String code) {

        if (isEmpty(code)) {
            return null;
        }

        SnsToken snsToken = SnsAPI.oauth2AccessToken(SystemConfig.getString(Constant.WX.APPID_KEY), SystemConfig.getString(Constant.WX.SECRET_KEY), code);

        return snsToken.getOpenid();
    }

    /**
     * 页面config值
     *
     * @return
     */
    public String getJsConfig(String url) {

        String[] jsApis = new String[]{
                "onMenuShareTimeline",
                "onMenuShareAppMessage",
                "hideMenuItems"
        };

        return JsUtil.generateConfigJson(jsApiTicketCache.getTicket(), false, SystemConfig.getString(Constant.WX.APPID_KEY), url, jsApis);
    }

    /**
     * 生成授权url
     *
     * @param url
     * @param state
     * @return
     */
    public String getShareUrl(String url, String state) {

        return SnsAPI.connectOauth2Authorize(SystemConfig.getString(Constant.WX.APPID_KEY), url, false, state);
    }

    public String getCurrentURL(HttpServletRequest request) {

        return request.getRequestURL() +
                (isEmpty(request.getQueryString()) ? "" : "?"+request.getQueryString());
    }
}
